﻿package fui.FUIData {
	import flash.display.Sprite;
	import flash.net.ObjectEncoding;
	import fui.FUIData.PHPRemoting.*;
	import fui.FUIData.IDBClient;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	public class DBClientV2 extends EventDispatcher implements IDBClient
	{
		// singleton
		private static var _instance:DBClientV2;
		//AMF gateway
		private var _gateway:String = "http://bogo.com/BOGO/amfphp/gateway.php";
		private static const _Procedure:String = "clientServices.";
		// PHPRemote object
		private var _p:Remoting;
		// RPC map
		private var responseObj:Object;
		
		public function DBClientV2(parameter:SingletonEnforcer):void
		{
		}
			
		/* real constructor. Args: HostName = Web server host name for AMFPHP */
		public static function getInstance(HostName:String, RootSprite:Sprite):DBClientV2
		{
	        if(_instance == null) 
				{
	            _instance = new DBClientV2(new SingletonEnforcer());
		
				// AMF3 is our desired protocol version BUT AMFPHP does not support it before v2.0 :(
				//	_instance.objectEncoding = ObjectEncoding.AMF0;

				
				
				// Gateway.php url for NetConnection
				_instance._gateway = "http://" + HostName + "/amfphp/gateway.php";
				
				// get PHPRemoting instance to work with
				_instance._p = Remoting.getInstance(RootSprite.root,_instance._gateway);
				}
			return _instance;
		}
		
		private function executeResponse(re:PHPResult):void
		{
			//_instance._ResponseArray = re.result[0] as Array;
			trace(re.result);
			trace("-------Type--------");
			trace(typeof(re.result));
			trace("---------------");
			trace(re.result.source);

			if(typeof(re.result) == "boolean")
			{
				responseObj = new Object();
				responseObj.rc = re.result;
			}
			else
			{
				if(re.result[0] == undefined)
				{
					responseObj = new Object();
					responseObj.rc = false;
				}
				else
				{
					
					responseObj = re.result[0];
					responseObj.rc = true;
				}
			}
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		public function get CallResponse():Object
		{
			trace (responseObj);
			return this.responseObj;
		}
		public function CallStoredProcedure(StoreProcedure:String, ... args):void
		{
			trace("---------------CallStoredProcedure-----------------");
			trace(args);
			
			var Procedure:String = _Procedure + StoreProcedure;
			var MySQLCall:PHPCall= new PHPCall(Remoting.PHP, executeResponse, Procedure, args);
		}
	}
}
class SingletonEnforcer {}